package br.com.ordersys.web;

import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import br.com.ordersys.framework.restlayer.auth.AuthenticationData;
import br.com.ordersys.web.utils.UserPictureUtils;

@Controller
public class FileUploadController {

	@RequestMapping(value = "/uploadUserPicture", method = RequestMethod.POST)
	public void handleFormUpload(HttpServletResponse resp, HttpServletRequest req, @RequestParam("fileContent") final MultipartFile file) {
		try {
			final AuthenticationData ad = (AuthenticationData) req.getSession().getAttribute(AuthenticationData.class.getName());

			ad.registry();

			if (!file.isEmpty()) {
				UserPictureUtils.saveFileOnTempFolder(req, file);
			} else {
				resp.setStatus(404);
			}

		} catch (Exception e) {
			e.printStackTrace();
			resp.setStatus(404);
		} finally {
			AuthenticationData.unregistryCurrent();
		}
	}

	@RequestMapping(value = "/getTmpPicture", method = RequestMethod.GET)
	public void getTmpPicture(HttpServletResponse resp, HttpServletRequest req) {
		try {
			final AuthenticationData ad = (AuthenticationData) req.getSession().getAttribute(AuthenticationData.class.getName());

			ad.registry();

			byte [] fileContent = UserPictureUtils.readFromTempFolder(req);
			
			if(fileContent != null){
				resp.setContentType("image/png");
				OutputStream out = resp.getOutputStream();
				out.write(fileContent);
				out.flush();
			}else{
				resp.setStatus(404);
			}
		} catch (Exception e) {
			e.printStackTrace();
			resp.setStatus(404);
		} finally {
			AuthenticationData.unregistryCurrent();
		}

	}

}